<template>
  <aside class="fixed inset-y-0 left-0 w-16 bg-purple-100 text-gray-600 flex flex-col items-center z-30">
    <!-- 用户头像/信息 -->
    <div class="mt-2 relative">
      <div class="w-12 h-12 rounded-full overflow-hidden border-2 border-blue-500">
        <img :src="loginStore.userInfo?loginStore.userInfo.avatarUrl:'https://picsum.photos/300/300?random=1'"
             alt="用户头像" class="w-full h-full object-cover">
      </div>
    </div>

    <!-- 主导航菜单 -->
    <nav class="flex-1 mt-6 w-full">
      <ul class="space-y-1">
        <li>
          <a href="#"
             @click.prevent="toRoute('/chats')"
             :class="{ 'text-blue-600 bg-blue-100/50': activeMenu === '/chats' }"
             class="flex items-center justify-center h-12 rounded-lg mx-2 transition-all hover:shadow-sm">
            <i class="fa-solid fa-comments text-2xl"></i>
            <span class="absolute right-2 bg-red-500 w-2 h-2 rounded-full"></span> </a>
        </li>
        <li>
          <a href="#"
             @click.prevent="toRoute('/contacts')"
             :class="{ 'text-blue-600 bg-blue-100/50': activeMenu === '/contacts' }"
             class="flex items-center justify-center h-12 rounded-lg mx-2 transition-all hover:shadow-sm">
            <i class="fa-solid fa-address-book text-2xl"></i>
          </a>
        </li>
        <li>
          <a href="#"
             @click.prevent="toRoute('/groups')"
             :class="{ 'text-blue-600 bg-blue-100/50': activeMenu === '/groups' }"
             class="flex items-center justify-center h-12 rounded-lg mx-2 transition-all hover:shadow-sm">
            <i class="fa-solid fa-users text-2xl"></i>
          </a>
        </li>
        <li>
          <a href="#"
             @click.prevent="toRoute('/notice')"
             :class="{ 'text-blue-600 bg-blue-100/50': activeMenu === '/notice' }"
             class="flex items-center justify-center h-12 rounded-lg mx-2 transition-all hover:shadow-sm">
            <i class="fa-solid fa-bell text-2xl"></i>
            <span class="absolute right-2 bg-red-500 text-white text-xs font-bold px-1 py-0 rounded-full">5</span>
          </a>
        </li>
        <li>
          <a href="#"
             class="flex items-center justify-center h-12 hover:text-blue-600 hover:bg-purple-200 hover:shadow-sm rounded-lg mx-2 transition-all"
             @click.prevent="clickAdd">
            <i class="fa-solid fa-plus text-2xl"></i>
          </a>
        </li>
      </ul>
    </nav>

    <!-- 底部操作区 -->
    <div class="w-full mb-6">
      <ul class="space-y-1">
        <li>
          <a href="#"
             class="flex items-center justify-center h-12 hover:text-blue-600 hover:bg-purple-200 hover:shadow-sm rounded-lg mx-2 transition-all">
            <i class="fa-solid fa-cog text-2xl"></i> <!-- Solid 风格设置图标 -->
          </a>
        </li>
        <li>
          <a href="#" @click="clickLogout"
             class="flex items-center justify-center h-12 hover:text-blue-600 hover:bg-purple-200 hover:shadow-sm rounded-lg mx-2 transition-all">
            <i class="fa-solid fa-sign-out text-2xl"></i> <!-- Solid 风格登出图标 -->
          </a>
        </li>
      </ul>
    </div>
  </aside>

  <!-- 主视窗区域 -->
  <div class="flex-auto h-screen overflow-auto ml-16">
    <router-view></router-view>
  </div>

  <DialogBox title="语音视频" :customSize="{high:'h-4/5',width:'w-full',max:'max-w-5xl'}" :dialogVisible="dialogVisible"
             @closed="close">
    <VideoCallPane ref="callPaneRef" :contact="contact" :callType="callType" :callState="callState"
                   @updateCallType="updateCallType" @updateCallState="updateCallState"  />
  </DialogBox>
</template>

<script setup lang="ts">
import {inject, onMounted, provide, reactive, ref, toRaw, watch} from 'vue'
import {useRoute, useRouter} from 'vue-router';
import {useLoginStore} from '../stores/login_store.ts'
import LoginApi from "@/api/login.js";
import VideoCallPane from "@/views/chatting_components/VideoCallPane.vue";
import DialogBox from "@/components/DialogBox.vue";
import {CallStatus} from "@/models/call.ts";
import {getCalleeRef} from "@/models/call_service.ts";
import {useContactStore} from "@/stores/contacts_store.ts";

const route = useRoute();
const router = useRouter();
const loginStore = useLoginStore();
const contactStore = useContactStore();

const signalWS = inject('signalWS');
const chatWS = inject('chatWS');

// 当前选中的菜单项
const activeMenu = ref(route.path);

const callPaneRef = ref(null);

const dialogVisible = ref(false);
const callType = ref(0);
const callParams = reactive({
  calleeId: '',
  isGroup: false,
});
const contact = ref({});

//通话状态数据
const callState = reactive({
  isRing: false, //是否来电了
  status: CallStatus.Noting,//通话状态：无通话、等待通话、正在通话
});

const updateCallType = (type:number) => {
  callType.value = type;
}
const updateCallState = (status: CallStatus, isRing: boolean) => {
  if (status != undefined) {
    callState.status = status
  }

  if (isRing != undefined) {
    callState.isRing = isRing
  }
}
watch(() => callState.isRing, (value, oldVal) => {
  console.log(`watch callState.isRing changed from ${oldVal} to ${value}`);
  if (value && !oldVal) {//当 isRing 由 false -> true 时触发弹框

    const callerId = getCalleeRef().value?.callerId;
    contact.value = toRaw(contactStore.getContactByUserId(callerId));
    console.log("ring contact = ",contact.value.nickname);

    dialogVisible.value = true;
  }
});

onMounted(() => {
  if (callPaneRef.value) {
    signalWS?.bindListener(callState, callPaneRef.value.signalHandle);
  }
})

const clickAdd = () => {
  console.log("click add...");
}

// 关闭弹框
const close = () => {
  dialogVisible.value = false;
  if (callPaneRef.value) {
    callPaneRef.value.endCall();
  }
}

// 打电话
const toCall = (type: number, calleeId: string, isGroup: boolean) => {
  console.log("click call... type = " + type + ",\t calleeId = " + calleeId + ",\t isGroup = " + isGroup);
  callType.value = type;
  callParams.calleeId = calleeId;
  callParams.isGroup = isGroup;

  contact.value = toRaw(contactStore.getContactByUserId(calleeId));
  console.log("call contact = ",contact.value.nickname);

  dialogVisible.value = true;

  if (callPaneRef.value) {
    callPaneRef.value.callOut(calleeId, isGroup);
  }
}

/* 注入名, 注入值 */
provide('toCall', toCall);

/**
 * 退出登录
 */
const clickLogout = async () => {
  try {
    console.debug("发送退出登录请求... ")
    await LoginApi.logOut();
    await loginStore.clearUserInfo();
    window.ipcRenderer?.logoutCallback();

    chatWS?.disconnect();
    signalWS?.disconnect();

    toRoute("/login");
  } catch (e) {
    console.error(e)
  }
}

/**
 * 路由
 * @param path
 */
const toRoute = (path: string) => {
  activeMenu.value = path;
  router?.replace({path: path})
}
/* 注入名, 注入值 */
provide('toRoute', toRoute);
</script>